package com.lzy.shops.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzy.shops.bean.*;
import com.lzy.shops.mapper.GoodsCartMapper;
import com.lzy.shops.mapper.GoodsMapper;
import com.lzy.shops.mapper.OrderMapper;
import com.lzy.shops.service.OrderService;
import com.lzy.shops.utils.OrderUtil;
import com.lzy.shops.utils.PageBeanUtils;
import com.lzy.shops.vo.GoodsInfoVo;
import com.lzy.shops.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper mapper;
    @Autowired
    private GoodsCartMapper goodsCartMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    // 购物车购买
    @Override
    public Boolean AddOrders(String userId,String ids,Date time,String payment_type,String orderId,String info,Integer money) {
        List<GoodsCart> lists = new ArrayList<>();
        int idsNums = ids.indexOf(",");
        /**
         * 购物车查找数据
         */
        if(idsNums!=-1){
            // 多个商品
            String[] idParams = ids.split(",");
            for (String id : idParams) {
                GoodsCart goods = findGoodsCar(id, userId);
                if(goods!=null){
                    lists.add(goods);
                }
            }
        }else{
            // 单个商品
            GoodsCart goodsCar = findGoodsCar(ids, userId);
            if(goodsCar!=null){
                lists.add(goodsCar);
            }
        }
        // 封装order
        List<Order> orderList = toOrder(lists, userId, time, payment_type,orderId,info,money);
        Integer count = 0; // 判断新增到数据库的数量
        for (Order order : orderList) {
            Integer integer = mapper.AddOrder(order);
            if (integer==1){
                count++;
            }
        }
        if(count == orderList.size()){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<OrderVo> findByUserOrder(Integer userid) {
        // 查找数据
        List<OrderVo> orderList = mapper.findByUserOrder(userid);
        // 同一订单商品合并
        /**
         * 不存在id则添加 存在则合并
         */
        List<String> orderIds = new ArrayList<>(); // 存放orderId
        List<OrderVo> datas = new ArrayList<>(); // 存放订单
        for (OrderVo orderVo : orderList) {
            if(orderIds.indexOf(orderVo.getOrder_id()) == -1){
                datas.add(orderVo);
                orderIds.add(orderVo.getOrder_id());
            }else{
                for (OrderVo data : datas) {
                    if(data.getOrder_id().equals(orderVo.getOrder_id())){
                        data.getLists().addAll(orderVo.getLists());
                    }
                }
            }
        }
        return datas;
    }

    @Override
    public Integer findByUserOrderNums(Integer userId) {
        return mapper.findByUserOrderNums(userId);
    }

    @Override
    public Integer delOrder(Integer userId, String orderId) {
        return mapper.delOrder(userId,orderId);
    }

    // 直接购买
    @Override
    public Boolean AddOrder(String userId, String info, Integer money, String paymentType, String orderId) {
        JSONArray objects = JSONObject.parseArray(info);
        Map maps = null;
        for (Object object : objects) {
            maps = JSONObject.parseObject(object.toString());
        }
        String shopId = maps.get("shopId").toString();
        Collection<Goods> goods = goodsMapper.findByGoodsId(Integer.parseInt(shopId));
        Order order = new Order();
        for (Goods good : goods) {
            order.setOrder_id(orderId);
            order.setState(1);
            Integer nums = Integer.valueOf((maps.get("nums").toString()));
            order.setPayment(Double.valueOf(money));
            order.setGoods_id(Long.parseLong(shopId));
            order.setGoods_nums(nums);
            order.setUser_id(Long.parseLong(userId));
            order.setPayment_time(new Date());
            order.setPayment_type(1);
        }
        Integer integer = mapper.AddOrder(order);
        if (integer==1){
            return true;
        }
        return false;
    }

    @Override
    public List<OrderVo> findAllOrder(Search search) {
        List<OrderVo> allOrder = mapper.findAllOrder(search);
        List<OrderVo> response = new ArrayList<>();
        List<String> ids = new ArrayList<>();
        for (OrderVo orderVo : allOrder) {
            if(ids.indexOf(orderVo.getOrder_id())==-1){
                ids.add(orderVo.getOrder_id());
                response.add(orderVo);
            }else{
                for (OrderVo data : response) {
                    if(data.getOrder_id().equals(orderVo.getOrder_id())){
                        data.getLists().addAll(orderVo.getLists());
                    }
                }
            }
        }
        return response;
    }

    @Override
    public Integer findAllOrderNums() {
        return mapper.findAllOrderNums();
    }

    // 通过购物车id和用户id查找商品数据
    private GoodsCart findGoodsCar(String carId,String userId){
        return goodsCartMapper.findByGoodsCar(Integer.parseInt(carId), Integer.parseInt(userId));
    }

    // 封装到order
    private List<Order> toOrder(List<GoodsCart> list, String userId, Date time,String payment_type,String orderId,String info,Integer money){
        List<Order> orderList = new ArrayList<>();
        // 获取商品信息
        JSONArray objects = JSONObject.parseArray(info);
        for (GoodsCart goodsCart : list) {
            Order order = new Order();
            // 向订单添加商品信息
            for (Object object : objects) {
                Map jsonObject = JSONObject.parseObject(object.toString());
                if(jsonObject.get("shopId").toString().equals(goodsCart.getShopId().toString())){
                    order.setGoods_id(goodsCart.getShopId());
                    Integer nums = Integer.valueOf((jsonObject.get("nums").toString()));
                    order.setGoods_nums(nums);
                    order.setPayment(Double.valueOf(money));
                }
            }
            order.setState(1);
            order.setUser_id(Long.parseLong(userId));
            order.setOrder_id(orderId);
            order.setPayment_time(time);
            order.setPayment_type(Integer.parseInt(payment_type));
            orderList.add(order);
        }
        return orderList;
    }
}
